import { Injectable } from '@nestjs/common';
import { CreateExebookDto } from './dto/create-exebook.dto';
import { UpdateExebookDto } from './dto/update-exebook.dto';
import { Exebook } from './entities/exebook.entity';
import { PageResultDto } from 'src/common/dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository,Like } from 'typeorm';
import { Dept } from '../../system/dept/entities/dept.entity';
import { Duty } from '../../system/duty/entities/duty.entity';

@Injectable()
export class ExebookService {
  constructor(   //创建Repository数据库操作
    @InjectRepository(Exebook)
    private exebooksRepository: Repository<Exebook>
  ) {}
 
  //:前面的是函数名称，后面的是返回值类型，返回值简单可以不写
  async AddExebook(addexebook: CreateExebookDto){
    //一对多，一对多，多对多存储的步骤：1、先创建对象  2、再把这两个对象挂到身上 3、保存到数据库
    const dept = new Dept();
    dept.Id = addexebook.deptId;   //创建Dept对象id等于前端传来的deptId
    const duty = new Duty();
    duty.Id = addexebook.dutyId;
    const exe_book= this.exebooksRepository.create(addexebook);  //根据前端创建实体对象
    exe_book.Dept = dept;
    exe_book.Duty = duty;
    await this.exebooksRepository.save(exe_book);  //保存到数据库
    return exe_book;
  }

  //获取题库列表
  async findAllbooks(querylistDto: any): Promise<PageResultDto<Exebook>> {
    let exebooks = await this.exebooksRepository.createQueryBuilder('exe_book')
      // .leftJoinAndSelect('exe_book.Role', 'Role')
      .skip((querylistDto.pageNum - 1) * querylistDto.pageSize)
      .take(querylistDto.pageSize)
      .getMany();
    
    let result = new PageResultDto<Exebook>();
    result.data = exebooks;
    result.total = await this.exebooksRepository.count();
    result.pageNum = querylistDto.pageNum;
    result.pageSize = querylistDto.pageSize;
    return result;
  }

  //根据id获取题目
  async findOnebook(id: string):  Promise<[boolean, Exebook]> {
    let exebook = await this.exebooksRepository.findOne({ where: { Id: id } });
    // console.log(exebook.Questiontext)   
    if (!exebook || exebook.Deleted === 1 ) {
      return [false, new Exebook()];
    }
    // console.log('查询用户成功', user);
    return [true, exebook];
  }
  
  // 题库题目模糊查询
  async findOneBytext(questiontext: string): Promise<[boolean, Exebook[]]> {
    const exebooks = await this.exebooksRepository.find({where: {Questiontext: Like(`%${questiontext}%`), Deleted: 0 } }); // 模糊查询，不包括已删除的题目
 
    if (!exebooks || exebooks.length === 0) {
      return [false, []]; // 返回空数组
    }
  
    console.log('题目模糊查询成功', exebooks);
    return [true, exebooks];
  }
  

  // 题库题目更新
  async updatebook(updateexebook: CreateExebookDto):  Promise<[boolean, string]> {
    // let exebook = await this.exebooksRepository.findOne({ where: { Id: updateexebook.Id }, relations: ['Role'] });
    let exebook = await this.exebooksRepository.findOne({ where: { Id: updateexebook.Id } });
    if (!exebook || exebook.Deleted === 1 ) {
      return [false, "更新失败，题目不存在"];
    }
    // 题库题目更新
    exebook = this.exebooksRepository.create(updateexebook);
    const dept = new Dept();
    dept.Id = updateexebook.deptId;
    const duty = new Duty();
    duty.Id = updateexebook.dutyId;
    await this.exebooksRepository.update(exebook.Id, {
      Questiontype:exebook.Questiontype,
      Questiontext:exebook.Questiontext,
      Options:exebook.Options,
      Tfanswer:exebook.Tfanswer,
      Fillanswer:exebook.Fillanswer,
      Explanation:exebook.Explanation,
      Difficulty:exebook.Difficulty,
      Dept: dept,
      Duty: duty,
    });
    return [true, "题目更新成功"];
  }

  //删除指定题目
  async removebook(id: string) :  Promise<[boolean, string]>{
    let rembook = await this.exebooksRepository.findOne({ where: { Id: id } });
    if (!rembook) {
      return [false, "题目不存在"];
    }else {
      // await this.exebooksRepository.delete(id);
      await this.exebooksRepository.update(id, { Deleted: 1 });
      return [true, "删除成功"];
    }
  }
  
}
